<?php
/**
 * Description: 获取代金券列表
 *
 * @author      Eden
 * @datetime    2016/12/22 19:57
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */

class Voucher_Model extends API_Model
{
    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 主程序
     * @param array $params
     */
    public function run($params = array())
    {
        $send['state'] = false;
        do {

            if (empty($params['userId'])) {
                $send['error'] = '参数错误';
                break;
            }

            $res = $this->getVoucher($params['userId']);
            $send['state'] = true;
            if (empty($res)) {
                $send['data'] = [];
            } else {
                $send['data'] = $res;
            }

        } while(false);
        $this->output->send($send);
    }

    /**
     * 获取代金券
     * @param int $userId
     * @return array|bool
     */
    private function getVoucher($userId = 0)
    {
        $db = clone($this->db);
        $nowTime = date('Y-m-d H:i:s');
        $q = $db->where("expires > '{$nowTime}'")->get_where('user_voucher', [
            'userId' => $userId,
            'status' => 1,
            'used' => 0
        ]);
        $rows = $q->result_array();
        if (empty($rows)) {
            return false;
        }

        $vouchers = [];
        foreach($rows as $item) {
            $vouchers[] = array(
                'voucherId' => intval($item['id']),
                'voucher' => value($item, 'voucher'),
                'money' => doubleval($item['money']),
                'created' => value($item, 'created'),
                'expires' => value($item, 'expires')
            );
        }

        return $vouchers;
    }
}
